package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.entity.vo.AttrGroupRelationVo;
import com.atguigu.gulimall.product.entity.vo.AttrGroupVo;
import com.atguigu.gulimall.product.service.AttrAttrgroupRelationService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.service.AttrGroupService;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;


@Service("attrGroupService")
public class AttrGroupServiceImpl extends ServiceImpl<AttrGroupDao, AttrGroupEntity> implements AttrGroupService {

    @Resource
    private CategoryDao CategoryDao;

    @Resource
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Resource
    private AttrDao attrDao;

    @Resource
    private AttrGroupDao attrGroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrGroupEntity> page = this.page(
                new Query<AttrGroupEntity>().getPage(params),
                new QueryWrapper<AttrGroupEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public IPage<AttrGroupEntity> selectPageInfo(Map<String, Object> params, String categoryId) {

        Page<AttrGroupEntity> page = new Page<AttrGroupEntity>(Long.parseLong((String) params.get("page")), Long.parseLong((String) params.get("limit")));
        long aLong = Long.parseLong(categoryId);
        if (StringUtils.isEmpty(categoryId)) {
            return baseMapper.selectPage(page, new QueryWrapper<AttrGroupEntity>());
        } else {

            QueryWrapper<AttrGroupEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("catelog_id", aLong);
            String key = (String) params.get("key");
            if (!StringUtils.isEmpty(key)) {
                wrapper.and((obj) -> {
                    obj.eq("attr_group_id", key).or().like("attr_group_name", key);
                });
            }
            IPage<AttrGroupEntity> selectPage = baseMapper.selectPage(page, wrapper);

            return selectPage;

        }
    }

    @Override
    public List<Long> selectCatelogPath(Long catelogId) {
        ArrayList<Long> arrayList = new ArrayList<>();
        selectParentId(catelogId,arrayList);
        Collections.reverse(arrayList);
        return arrayList;
    }

    @Override
    public List<AttrEntity> selectReletionattr(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> attrGroup = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));

        List<Long> list = attrGroup.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        if (list.size() == 0 || list == null){
            return null;
        }

        List<AttrEntity> attrEntityList = attrDao.selectBatchIds(list);
//        List<AttrEntity> attr = attrDao.selectbyIds(attrGroup);

        return attrEntityList;

    }

    @Override
    public void deleteReletionById(List<AttrGroupRelationVo> list) {
        attrGroupDao.deleteReletion(list);
    }

    /**
     * 查询当前分组下的no属性
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils selectRelationNoAttr(Map<String, Object> params, Long attrgroupId) {
        //查询当前分组属性
        List<AttrAttrgroupRelationEntity> relationEntities =
                attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>());
        List<Long> collectList = relationEntities.stream().map((relation) -> {
            return relation.getAttrId();
        }).collect(Collectors.toList());
        Page<AttrEntity> page = new Page<>(Long.parseLong((String) params.get("page")), Long.parseLong((String) params.get("limit")));
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.notIn("attr_id",collectList.toArray());
        wrapper.eq("attr_type",ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        //判断是否有模糊查询的属性
        String key = (String) params.get("key");
        if (StringUtils.isEmpty(key)){
            wrapper.and((obj)->{
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        //调用分页查询
        IPage<AttrEntity> attrEntityIPage = attrDao.selectPage(page, wrapper);
//        List<AttrEntity> list = attrDao.selectBatchIds(collectList);
        PageUtils pageUtils = new PageUtils(attrEntityIPage);


        return pageUtils;
    }

    @Override
    public void saveRelation(List<AttrGroupRelationVo> attrGroupRelationVo) {


        for (int i =0;i<attrGroupRelationVo.size();i++){
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrGroupRelationVo.get(i),attrAttrgroupRelationEntity);
            attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
        }


    }

    //获取分组信息及分组下的绑定信息
    @Override
    public List<AttrGroupVo> selectRelationAndAttr(Long catelogId) {
        //查询分组表
        List<AttrGroupEntity> catelogidList = baseMapper.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //封装属性
        List<AttrGroupVo> attrGroupVoList = catelogidList.stream().map(attrGroupEntity -> {
            AttrGroupVo attrGroupVo = new AttrGroupVo();
            BeanUtils.copyProperties(attrGroupEntity, attrGroupVo);
            //根据分组关联表查询attrid
            List<AttrAttrgroupRelationEntity> attrgroupRelationEntityList =
                    attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupEntity.getAttrGroupId()));
            if (attrgroupRelationEntityList!=null&&attrgroupRelationEntityList.size()!=0) {
                //将id封装成集合方便查询
                List<Long> collect = attrgroupRelationEntityList.stream().map(attrAttrgroupRelationEntity -> {
                    return attrAttrgroupRelationEntity.getAttrId();
                }).collect(Collectors.toList());
                List<AttrEntity> attrs = attrDao.selectBatchIds(collect);
                //放到返回给前端封装的Vo对象中
                attrGroupVo.setAttrs(attrs);
            }
            return attrGroupVo;
        }).collect(Collectors.toList());
        return attrGroupVoList;
    }


    /**
     * 查询路径
     * @param catelogId
     * @param list
     * @return
     */
    public List<Long> selectParentId(Long catelogId,ArrayList<Long> list){
        list.add(catelogId);
        CategoryEntity categoryEntity = CategoryDao.selectById(catelogId);
        Long parentCid = categoryEntity.getParentCid();
        if (parentCid!=0){
            selectParentId(parentCid,list);
        }
        return list;
    }

}